package com.cn.lb;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.cn.utils.SaplingConstant;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

import java.util.Map;

/**
 * @author: chenyuncong
 * @Date: 2019/12/7 11:05
 */
public class NacosInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        applicationContext.getBeanFactory().addBeanPostProcessor(new InstantiationAwareBeanPostProcessorAdapter(){
            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if(bean instanceof NacosDiscoveryProperties){
                    ConfigurableEnvironment environment = applicationContext.getEnvironment();
                    NacosDiscoveryProperties properties = (NacosDiscoveryProperties) bean;
                    Map<String,String> metaData = properties.getMetadata();
                    metaData.put(SaplingConstant.SERVICE_VERSION,environment.getProperty(SaplingConstant.SERVICE_VERSION));
                    metaData.put(SaplingConstant.SERVICE_GROUP,environment.getProperty(SaplingConstant.SERVICE_GROUP));
                    metaData.put(SaplingConstant.SERVICE_ENABLED,environment.getProperty(SaplingConstant.SERVICE_ENABLED));
                }
                return bean;
            }
            /*@Override
            public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
                if(bean instanceof NacosDiscoveryProperties){
                    ConfigurableEnvironment environment = applicationContext.getEnvironment();
                    NacosDiscoveryProperties properties = (NacosDiscoveryProperties) bean;
                    Map<String,String> metaData = properties.getMetadata();
                    metaData.put("version","1000");
                    metaData.put("group","g1");
                }
                return  super.postProcessAfterInstantiation(bean, beanName);
            }*/
        });
    }
}
